// pages/myself/merchant/MerchantCoupon.js
let network = null;
let utils = null;
let api = null;
const app = getApp();
var Zan = require('../../../dist/index.js');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');
var start01 = 0;
var start02 = 0;
Page(Object.assign({}, Zan.TopTips, Zan.Toast, Zan.Tab, {

  /**
   * 页面的初始数据
   */
  data: {
    tab: {
      list: [{
        id: 0,
        title: '进行中'
      }, {
        id: 1,
        title: '已下架'
      }],
      selectedId: 0,
      scroll: false
    },
    items: [{ a: '1', isTouchMove: false }, { a: '2', isTouchMove: false }, { a: '3', isTouchMove: false }, { a: '4', isTouchMove: false }],
    startX: 0, //开始坐标
    startY: 0,
    nodata: {
      msg: '暂无数据',
      notype: 1,
      imgurl: '/images/nodatas.png',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("RefreshMerchantCoupon", this.refreshNotification, this);
    WxNotificationCenter.addNotification("RefreshDownCoupon", this.refreshDownCoupon, this);
    WxNotificationCenter.addNotification("RefreshOnCoupon", this.refreshOnCoupon, this);
    WxNotificationCenter.addNotification("RefreshStoreCount", this.refreshStoreCount, this);

    this.data.tab.selectedId = options.index;
    this.setData({
      tab: this.data.tab,
    })
    this.setData({
      activeIndex: options.index
    })

    this.setData({
      BrandId: options.BrandId,
      name: decodeURIComponent(options.name),
      img: options.img,
      count: options.count,
      tenantType: options.tenantType,
      type: options.type,
      end: options.end
    })
    console.log(options.end) 
    console.log(new Date().getTime()) 
    this.onPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshMerchantCoupon", this);
    WxNotificationCenter.removeNotification("RefreshDownCoupon", this);
    WxNotificationCenter.removeNotification("RefreshOnCoupon", this);
    WxNotificationCenter.removeNotification("RefreshStoreCount", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    if (this.data.tab.selectedId == 0) {
      start01 = 0;
      this.setData({
        items: []
      })
      network._post_page_json(this, api.brandCouponList, start01, { brandId: this.data.BrandId, status: 1 }, success00);
    } else {
      start02 = 0;
      this.setData({
        items: []
      })
      network._post_page_json(this, api.brandCouponList, start02, { brandId: this.data.BrandId, status: 0 }, success02);
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  /**
   * 弹出框开关
   */
  // toggleDialog() {
  //   this.setData({
  //     showDialog: !this.data.showDialog
  //   })
  // },

  /**
   * 编辑品牌
   */
  goAddBrand: function (e) {
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/myself/merchant/EditBrand?brandId=' + this.data.BrandId + '&name=' + encodeURIComponent(this.data.name) + '&img=' + this.data.img + '&type=' + this.data.type
      })
    }
  },

  /**
   * 到期续费
   */
  goBrandRenew: function (e) {
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/myself/merchant/BrandRenew?brandId=' + this.data.BrandId + '&type=' + this.data.tenantType,
      })
    }
  },

  /**
   * 入进VIP升级
   */
  goUpgradeVIP: function (e) {
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/myself/merchant/UpgradeVIP',
      })
    }
  },

  /**
   * 进入发布优惠券
   */
  goSendCoupon: function (e) {
    if (utils.canTap(e)) {
      if (this.data.count) {
        wx.navigateTo({
          url: '/pages/myself/send/SendCoupon?BrandId=' + this.data.BrandId
        })
      } else {
        this.showZanTopTips(that.prompt, '请先创建门店');
      }
    }
  },

  /**
   * 进入店铺设置
   */
  goStoreSet: function (e) {
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/myself/merchant/StoreSet?BrandId=' + this.data.BrandId
      })
    }
  },

  /**
   * 进入优惠券详情
   */
  goCouponDetails: function (e) {
    wx.navigateTo({
      url: '/pages/myself/merchant/MerchantCouponDetails?couponId=' + e.currentTarget.dataset.couponid,
    })
  },

  /**
   * 手指触摸动作开始 记录起点X坐标
   */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.items.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },

  /**
   * 滑动事件处理
   */
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.items.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      items: that.data.items
    })
  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  /**
   * 上下架
   */
  release: function (e) {
    var delIndex = e.currentTarget.dataset.index;
    var status = e.currentTarget.dataset.status;
    var couponId = e.currentTarget.dataset.couponid;
    var shopCart = this.data.items[delIndex];
    if (status == 1) {
      network._post_json(this, api.onDownCoupon, { brandId: this.data.BrandId, couponId: couponId, status: 0 }, redownSuccess)
    } else {
      network._post_json(this, api.onDownCoupon, { brandId: this.data.BrandId, couponId: couponId, status: 1 }, reonSuccess);
    }


  },

  /**
   * 编辑
   */
  edit: function (e) {
    var delIndex = e.currentTarget.dataset.index;
    var shopCart = this.data.items[delIndex];
    var status = e.currentTarget.dataset.status;
    var couponId = e.currentTarget.dataset.couponid;
    if (couponId && status == 0) {
      if (utils.canTap(e)) {
        wx.navigateTo({
          url: '/pages/myself/send/EditCoupon?couponId=' + couponId + '&status=' + status + '&BrandId=' + this.data.BrandId
        })
      }
    }

  },

  /**
   * 删除事件
   */
  del: function (e) {
    var delIndex = e.currentTarget.dataset.index;
    var shopCart = this.data.items[delIndex];
    var couponId = e.currentTarget.dataset.couponid;
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delCoupon, { couponId: couponId }, delSuccess);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  handleZanTabChange(e) {
    var componentId = e.componentId;
    var selectedId = e.selectedId;

    this.setData({
      [`${componentId}.selectedId`]: selectedId
    })

    this.setData({
      activeIndex: selectedId
    })

    if (this.data.tab.selectedId == 0) {
      start01 = 0;
      this.setData({
        items: []
      })
      network._post_page_json(this, api.brandCouponList, start01, { brandId: this.data.BrandId, status: 1 }, success00);
    } else {
      start02 = 0;
      this.setData({
        items: []
      })
      network._post_page_json(this, api.brandCouponList, start02, { brandId: this.data.BrandId, status: 0 }, success02);
    }

  },

  /**
   * 刷新门店数量
   */
  refreshStoreCount: function (count) {
    this.setData({
      count: parseInt(this.data.count) + parseInt(count)
    })
  },


  /**
   * 刷新品牌信息
   */
  refreshNotification: function (obj) {
    console.log(obj)
    this.setData({
      BrandId: obj.brandId,
      name: obj.name,
      img: obj.img
    })
  },

  /**
   * 优惠券上架之后刷新
   */
  refreshOnCoupon: function (types) {
    if (types == 1) {
      this.showZanToast('上架成功！');
    } else if (types == 2) {
      this.showZanToast('优惠券删除成功！');
    } else {
      this.showZanToast('编辑优惠券成功，待上架！');
    }
    network._post_page_json(this, api.brandCouponList, start01, { brandId: this.data.BrandId, status: 0 }, success00);
  },
  /**
   * 优惠券下架之后刷新
   */
  refreshDownCoupon: function (obj) {
    if (obj == true) {
      this.showZanToast('下架成功！');
      network._post_page_json(this, api.brandCouponList, start01, { brandId: this.data.BrandId, status: 1 }, success02);
    } else {
      this.setData({
        tab: {
          list: [{
            id: 0,
            title: '进行中'
          }, {
            id: 1,
            title: '已下架'
          }],
          selectedId: 1,
          scroll: false
        }
      })
      network._post_page_json(this, api.brandCouponList, start01, { brandId: this.data.BrandId, status: 0 }, success02);
    }
  }
}))

var success00 = function (that, res) {
  if (res.data.data) {
    that.setData({
      items: res.data.data
    })
  }
}

var success02 = function (that, res) {
  if (res.data.data) {
    that.setData({
      items: res.data.data
    })
  }
}

var redownSuccess = function (that, res) {
  that.onPullDownRefresh()
  that.showZanToast('下架成功！');
}

var reonSuccess = function (that, res) {
  that.onPullDownRefresh()
  that.showZanToast('上架成功！');
}

var delSuccess = function (that, res) {
  that.onPullDownRefresh()
  that.showZanToast('优惠券删除成功！');
}